package com.gqyin.demo.controller;

import com.gqyin.demo.annotation.Loggable;
import com.gqyin.demo.common.CommonResult;
import com.gqyin.demo.domain.User;
import com.gqyin.demo.domain.UserQueryParam;
import com.gqyin.demo.service.UserService;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * @author guiqing.yin
 * 2024-03-28 14:24
 */
@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public CommonResult<List<User>> getAllUsers() {
        List<User> allUsers = userService.findAll();
        return CommonResult.success(allUsers);
    }

    @GetMapping("/{id}")
    public CommonResult<User> getUserById(@PathVariable String id) {
        Validate.notBlank(id, "'id' must not be blank");
        User user = userService.findById(id);
        return CommonResult.success(user);
    }

    @GetMapping("/name")
    public CommonResult<User> queryUserByName(@RequestParam String name) {
        Validate.notBlank(name, "'name' must not be blank");
        User user = userService.findByName(name);
        return CommonResult.success(user);
    }

    @Loggable
    @PostMapping("/query")
    public CommonResult<Page<User>> query(@NotNull @RequestBody UserQueryParam queryParam) {
        Map<String, Sort.Direction> orders = queryParam.getOrders();
        Page<User> userPage = userService.query(queryParam);
        return CommonResult.success(userPage);
    }

    @Loggable
    @PostMapping
    public CommonResult<User> createUser(@Valid @RequestBody User user) {
        User savedUser = userService.save(user);
        return CommonResult.success(savedUser);
    }

    @Loggable
    @PatchMapping("/{id}")
    public CommonResult<User> updateUserById(@Valid @RequestBody User user, @NotBlank @PathVariable String id) {
        user.setId(id);
        User updatedUser = userService.updateById(user, id);
        return CommonResult.success(updatedUser);
    }

    @Loggable
    @DeleteMapping("/{id}")
    public CommonResult<User> deleteUserById(@PathVariable String id) {
        Validate.notBlank(id, "'id' must not be blank");
        User user = userService.deleteById(id);
        return CommonResult.success(user);
    }
}
